// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

import App from './App.vue'
import router from './router'
/* import axios from 'axios'; */
import ElementUI from 'element-ui'
import store from './store'
import axios from 'axios'
import iView from 'iview'
import 'iview/dist/styles/iview.css'
import { Message } from 'iview'
import 'element-ui/lib/theme-chalk/index.css'
var VueCodeMirror = require('vue-codemirror-lite')
Vue.use(VueCodeMirror);
Vue.use(ElementUI);
Vue.component('Message', Message)
Vue.use(iView)
Vue.config.productionTip = false

axios.interceptors.request.use(request => {
    const token = window.localStorage.getItem('token');
    if (token) {
        // 此处有坑，下方记录
        request.headers['authorization'] =`Bearer ${token}`;
    }
    return request;
}, err => {
    return Promise.reject(err)
})

axios.interceptors.response.use((response) => {
    if (response.data.token) {
      window.localStorage.setItem('token', response.data.token);
    }
    return response;
}, (error) => {
    if (error.response) {
        switch (error.response.status) {
            case 401:
                store.commit('del_token')
                router.push('/login')
        }
        Message.error('登录信息失效，请重新登录')
    }
    return Promise.reject(error.response.data)
})

router.beforeEach((to, from, next) => {
    if (to.meta.required) {
        if (process.env.NODE_ENV === 'development') {
            // console.log(localStorage, sessionStorage)
        }
        const token = window.localStorage.getItem('token');
        if (token) {
            store.commit('set_token', {
                token: localStorage.token,
                UUID: localStorage.UUID,
                user: localStorage.user
            })
            axios.defaults.auth = {
                UUID: store.state.UUID,
                token: store.state.token
            }
            iView.LoadingBar.start();
            next()
        } else {
            next({
                path: '/login',
            })
        }
    } else {
        iView.LoadingBar.start();
        next()
    }
})

// 创建事件
var evt = document.createEvent('Event');
// 定义事件类型
evt.initEvent('customEvent', true, true);

router.afterEach((to, from, next) => {
    iView.LoadingBar.finish();
    window.dispatchEvent(evt)
})


Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    store,
    router,
    components: { App },
    template: '<App/>'
})